import os  
import psutil  
import time  
import multiprocessing  

import logging;

logger = logging.getLogger('mylogger')
logger.setLevel(logging.DEBUG)

# 2、创建一个handler，用于写入日志文件
fh = logging.FileHandler('test.log')
fh.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

# 4、给handler添加formatter
fh.setFormatter(formatter)

logger.addHandler(fh)

def get_pid_memory(pid):  
    """  
    根据进程号来获取进程的内存大小  
    :param pid: 进程id  
    :return: pid内存大小/MB  
    """  
    process = psutil.Process(pid)  
    mem_info = process.memory_info()  
    return mem_info.rss / 1024 / 1024  


def get_process_memory(process_name):  
    """  
    获取同一个进程名所占的所有内存  
    :param process_name:进程名字  
    :return:同一个进程名所占的所有内存/MB  
    """  
    total_mem = 0  
    for i in psutil.process_iter():  
        if i.name() == process_name:  
            total_mem += get_pid_memory(i.pid)  
    print('{:.2f} MB'.format(total_mem))  
    return total_mem  

if __name__ == "__main__":
    pid = 7531
    while True:
        memory = get_pid_memory(pid)
        print(memory)
        logger.debug("memory: [%s]", memory)

        time.sleep(60*60)
